package org.jianfa.mq.seckill.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jianfa.mq.seckill.entity.CodeMsg;
import org.jianfa.mq.seckill.entity.po.OrderInfo;
import org.jianfa.mq.seckill.entity.po.Users;
import org.jianfa.mq.seckill.entity.vo.Result;
import org.jianfa.mq.seckill.mapper.OrderInfoMapper;
import org.jianfa.mq.seckill.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
public class OrderController {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @GetMapping("/seckill/orderList")
    public Result<List<OrderInfo>> orderList() {
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        String username = (String) principal;
        Users users = usersMapper.selectByUsername(username);

        List<OrderInfo> orderInfos = orderInfoMapper.selectByUserId(users.getId().longValue());
        return Result.success(orderInfos);
    }

    @PostMapping("/seckill/payOrder")
    public Result<Integer> payOrder(@RequestParam("orderId") long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);
        if (orderInfo == null) {
            return Result.error(CodeMsg.ORDER_NOT_EXIST);
        }

        orderInfo.setStatus(1);
        orderInfo.setPayDate(new Date());
        return Result.success(1);
    }
}
